#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2010 - BidiX@BidiX.info
#
#
'''
    Base RequestHandler for app
        - use template
    Functions
        render()
'''
import os
import datetime

from google.appengine.ext import webapp
from webob import Request

from google.appengine.ext.webapp import template

from bidix import user

class RequestHandler(webapp.RequestHandler):
    '''
        Display the container of the page
        
    '''
    template_dir = os.path.join(os.path.dirname(__file__), 'template/')
 
    def _format_user(self):
        '''
        return a user context with :
            - title : Admin | User
            - name : user.nickname
            - url : login_url | logout_url
            - link_text : for url
            '''
        current_user = user.get_current_user()
        user_context = {}
        if current_user:
            if current_user.is_admin():
                user_context['title'] = 'Admin'
            else:
                user_context['title'] = 'User'
            user_context['name'] = current_user.nickname() + " | "
            user_context['url'] = user.logout_url(self.request.url)
            user_context['link_text'] = 'logout'
        else:
            user_context['title'] = ''
            user_context['url'] = user.login_url(self.request.url)
            user_context['link_text'] = 'login'
        return user_context
    
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        self.template = 'base.html'
        self.app_path = '/'+self.request.path.split('/')[1] 

   
    def render(self, context):
        '''
            update 'base_context' with 'context'
            use 'template' of context to render 'context' to output
        '''
        base_context = {
                        'template': self.template,
                        'title': 'Base page',
                        'app_path': self.app_path,
                        'user': self._format_user(),
                        'copyright': "Copyright &copy; 2009-%s - <a href=\"http://bidix.info\">BidiX</a>"%datetime.datetime.now().strftime("%Y")
                        }
        base_context.update(context)
        
        self.response.out.write(template.render( RequestHandler.template_dir+base_context['template'], base_context))
